import { Provide, Inject } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { StationFile, StationMeta } from '../entity/station-data.entity';
import {
  StationFileUploadResultDTO, StationMetaCreateDTO, StationMetaListDTO, IdDTO
} from '../dto/station-data.dto';
import * as path from 'path';
import * as fs from 'fs/promises';

@Provide()
export class StationDataService {
  @InjectEntityModel(StationFile)
  fileRepo: Repository<StationFile>;

  @InjectEntityModel(StationMeta)
  metaRepo: Repository<StationMeta>;

  // 保存上传文件到本地并入库
  /* async saveUploadFile(file) {
    // 兼容不同upload包版本
    const src = file.filepath || file.data;
    if (!src) {
      throw new Error('File path not found! file=' + JSON.stringify(file));
    }
  
    const ext = path.extname(file.filename);
    const uploadDir = path.join(__dirname, '../../upload');
    await fs.mkdir(uploadDir, { recursive: true });
    const fileKey = `${Date.now()}-${Math.random().toString(36).slice(2,8)}${ext}`;
    const dest = path.join(uploadDir, fileKey);
  
    // 拷贝文件
    await fs.copyFile(src, dest);
  
    // （可选：删除临时上传文件）
    // await fs.unlink(src);
  
    // ==== 数据库存储 ====
    const entity = this.fileRepo.create({
      fileKey,
      originalName: file.filename,
      filePath: dest,
      mimeType: file.mimeType || file.mime,  // 注意实体字段要有mimeType（统一）
      size: file.size,
    });
    // 写入数据库
    const saved = await this.fileRepo.save(entity);
  
    // 返回数据库中的记录，包括id
    return {
      id: saved.id,
      fileKey: saved.fileKey,
      filePath: saved.filePath,
      originalName: saved.originalName,
      mimeType: saved.mimeType,
      size: saved.size,
      uploadTime: saved.uploadTime
    };
  } */
  async saveUploadFile(file) {
    const src = file.filepath || file.data;
    if (!src) {
      throw new Error('File path not found! file=' + JSON.stringify(file));
    }
    // 真实获取物理文件大小
    let realSize = 0;
    try {
      const stat = await fs.stat(src);
      realSize = stat.size;
    } catch {
      realSize = 0;
    }

    // ...文件COPY代码
    const ext = path.extname(file.filename);
    const uploadDir = path.join(__dirname, '../../upload');
    await fs.mkdir(uploadDir, { recursive: true });
    const fileKey = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}${ext}`;
    const dest = path.join(uploadDir, fileKey);
    await fs.copyFile(src, dest);

    // 真实写入size
    const entity = this.fileRepo.create({
      fileKey,
      originalName: file.filename,
      filePath: dest,
      mimeType: file.mimeType || file.mime,
      size: realSize,
    });
    const saved = await this.fileRepo.save(entity);

    return {
      id: saved.id,
      fileKey: saved.fileKey,
      filePath: saved.filePath,
      originalName: saved.originalName,
      mimeType: saved.mimeType,
      size: saved.size,
      uploadTime: saved.uploadTime
    };
  }

  // 写元信息
  async createMetaInfo(dto: StationMetaCreateDTO) {
    // 确认文件存在
    const file = await this.fileRepo.findOneBy({ fileKey: dto.fileKey });
    if (!file) throw new Error('File not found, please re-upload');
    const entity = this.metaRepo.create({
      fileKey: dto.fileKey,
      stationId: dto.stationId,
      stationTypeId: dto.stationTypeId,
    });
    return await this.metaRepo.save(entity);
  }

  // 查询元信息(分页)
  async metaList(query: StationMetaListDTO, page = 1, pageSize = 10) {
    const where = {};
    if (query.stationId) where['stationId'] = query.stationId;
    if (query.stationTypeId) where['stationTypeId'] = query.stationTypeId;
    const [list, total] = await this.metaRepo.findAndCount({
      where,
      skip: (page - 1) * pageSize,
      take: pageSize,
      order: { createTime: 'DESC' }
    });
    return { list, total, page, pageSize };
  }

  // 下载
  async getFileByKey(fileKey: string) {
    return await this.fileRepo.findOneBy({ fileKey });
  }

  // 删除
  async deleteMeta(id: string) {
    const meta = await this.metaRepo.findOneBy({ id });
    if (!meta) throw new Error('Not found');
    await this.metaRepo.delete({ id });
  }
}
